package functions.ems_accountant_job_pool;

import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import com.beans.AccountingPoolGroupUserBean;
import com.beans.ClaimBean;
import com.crc.mam.BaseCase;
import coms.AutoException;
import coms.Constants;
import coms.JSONToBean;
import frame.HttpHelper;
import frame.InterTest;



public class Pool extends BaseCase {
	
    private org.slf4j.Logger logger = LoggerFactory.getLogger(Pool.class);

	String claimNumber;
	String result;
	String claimProcTaskInfoList;
	String procTaskInfoList;
	String proid;
	int actId = 1;
	AccountingPoolGroupUserBean accountAuditUser;
	
	public AccountingPoolGroupUserBean getAccountAuditUser() {
    return accountAuditUser;
  }

  public void setAccountAuditUser(AccountingPoolGroupUserBean accountAuditUser) {
    this.accountAuditUser = accountAuditUser;
  }

  AccountGroupWork group;
	
	public String getProid() {
		return proid;
	}

	public void setProid(String proid) {
		this.proid = proid;
	}

	public String getClaimNumber() {
		return claimNumber;
	}

	public void setClaimNumber(String claimNumber) {
		this.claimNumber = claimNumber;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public boolean isPassed() {
		return isPassed;
	}

	public void setPassed(boolean isPassed) {
		this.isPassed = isPassed;
	}

	public ClaimBean getClaimBean() {
		return claimBean;
	}

	public void setClaimBean(ClaimBean claimBean) {
		this.claimBean = claimBean;
	}

	boolean isPassed=false;

	ClaimBean claimBean;
	
	public Pool(String claimNumber,int actId) {
		this.claimNumber = claimNumber;
		this.actId = actId;

	}
	
	/**
	 * 未分配小组 - 通过报账单查询
	 * listUrl="/ems-accountant-job-pool/pool/draft/list";
	 */
	public void list() {
		logger.info("未分配小组 - 通过报账单查询 ---------------start ---------");
		String params = "{\"page\":{\"currentPage\":1,\"pageSize\":10,\"recordCount\":1},"
		    + "\"params\":{\"claimNum\":\""+claimNumber+"\",\"applicant\":\"\"},"
		    + "\"sortDTO\":{\"fieldName\":\"\",\"orderBy\":\"\"}}";
        logger.info("list params --- " + params);
		String url = "";
		if(actId == 1) {
			url =  Constants.LIST_URL;
		}else if(actId == 2) {
			url = Constants.REVIEW_LIST_URL;
		}else {
			url =  Constants.LIST_URL;
		}
		try {
			result = HttpHelper.post(params, url);
			logger.info("list--------" + result);
			status = HttpHelper.isOk;
			if(status) {
			  try {
				JSONObject object = new JSONObject(result);
				int total = object.getInt("total");
				if(total == 1) {
					JSONArray array = object.getJSONArray("list");
					JSONObject datas = array.getJSONObject(0);
					JSONObject procTaskInfo = datas.getJSONObject("procTaskInfo");
					claimProcTaskInfoList = "{\"claimProcTaskInfoList\":["+procTaskInfo.toString()+"]}";
					String claimNum = datas.getString("claimNum");
					if(claimNum.equals(claimNumber)) {
					    status = true;
					    String jsonString = datas.toString();
					    jsonString = jsonString.replace("claimNum", "claimNo");
					    logger.info(jsonString);
						claimBean = JSONToBean.parseJson2Object(ClaimBean.class, jsonString);
						remark = claimBean.toString();
						logger.info(remark);
					}else {
					  status = false;
					  remark = "serch key is \" + claimNumber + \",but found ";
					  logger.info(remark);
						//throw new AutoException("serch key is " + claimNumber + ",but found " + claimNum);
					}
				}else {
				  status = false;
				  logger.info(remark);
				  remark = claimNumber + " not found";
				//	throw new AutoException(claimNumber + " not found");
				}
			  }catch(JSONException e) {
				e.printStackTrace();
				remark = "JSON解析错误";
			  }
			}else {
			  try {
			    JSONObject object = new JSONObject(result);
			    remark = object.getString("message");
			    logger.info(remark);
			  }catch(JSONException e) {
			    e.printStackTrace();
			    remark = "JSON解析异常";
			  }
			}
			
		} catch (Exception e) {
		  status = false;
		  remark = "系统异常";
			e.printStackTrace();
		}
		logger.info("未分配小组 - 通过报账单查询 ---------------end ---------");
	}

	/**
	 * 未分配小组- 重新分配
	 * groupingUrl="/ems-accountant-job-pool/pool/draft/grouping"
	 * reviewGroupingUrl="/ems-accountant-job-pool/pool/review/grouping"
	 */
	public void grouping( ) {
		logger.info("未分配小组 - 重新分配 ---------------start ---------");
		String params = claimProcTaskInfoList;
		String url = "";
		if(actId == 1) {
			url = Constants.GROUPING_URL;
		}else if(actId == 2) {
			url = Constants.REVIEW_GROUPING_URL;
		}else {
			url = Constants.GROUPING_URL;
		}
		try {
			result = HttpHelper.post(params, url);
			status = HttpHelper.isOk;
			logger.info("grouping--------" + result);
			if(status) {
			  
			}else {
			  try {
			    JSONObject object = new JSONObject(result);
                remark = object.getString("message");
                logger.error(remark);
			  }catch(JSONException e) {
			    e.printStackTrace();
			   remark = "JSON解析错误";
			  }
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		logger.info("未分配小组 - 重新分配 ---------------end ---------");
	}
	
	/**
	 * 小组未分配- 通过报账单查询
	 * unassignedListUrl="/ems-accountant-job-pool/pool/draft/unassigned/list"
	 * reviewUnassignedListUrl="/ems-accountant-job-pool/pool/review/unassigned/list"
	 */
	public void unassignedList() {
		logger.info("小组未分配- 通过报账单查询 ---------------start ---------");
		String params = "{\"page\":{\"currentPage\":1,\"pageSize\":10,\"recordCount\":1},\"params\":{\"claimNum\":\""+claimNumber+"\",\"applicant\":\"\"},"
				+ "\"sortDTO\":{\"fieldName\":\"\",\"orderBy\":\"\"}}";
		String url = "";
		if(actId == 1) {
			url =  Constants.UNASSIGNED_LIST_URL;
		}else if(actId ==2) {
			url = Constants.REVIEW_UNASSIGNED_LIST_URL;
		}else {
			url = Constants.UNASSIGNED_LIST_URL;
		}
		try {
			result = HttpHelper.post(params, url);
			logger.info("unassignedList result--------" + result);
			status = HttpHelper.isOk;
			if(status) {
			  try {
				JSONObject object = new JSONObject(result);
				int total = object.getInt("total");
				if(total >0) {
				  JSONArray array = object.getJSONArray("list");
				  int arraySize = array.length();
				  JSONObject datas = array.getJSONObject(0);
				  JSONObject procTaskInfo = datas.getJSONObject("procTaskInfo");
					//JSONObject global = procTaskInfo.getJSONObject("globalVariables");
				  proid = procTaskInfo.getString("procesInstanceID");
				      /*System.out.println(proid);*/
				  if(actId == 1) {
				    procTaskInfo.put("actID", "GXKJCCS_010");
				    procTaskInfoList = "{\"claimProcTaskInfoList\":[" + procTaskInfo.toString();
				   }else if(actId == 2) {
				     procTaskInfo.put("actID", "GXKJCFS_020");
					 procTaskInfoList = "{\"claimProcTaskInfoList\":[" + procTaskInfo.toString();
				    }else {
				      procTaskInfo.put("actID", "GXKJCCS_010");
				      procTaskInfoList = "{\"claimProcTaskInfoList\":[" + procTaskInfo.toString()+"],\"userId\":27651}";
				    }
				    logger.info("procTaskInfo param--------->"+procTaskInfo.toString());					
				    logger.info("procTaskInfoList param -------->" + procTaskInfoList);
				}else {
				  status = false;
				  remark = "search "+claimNumber+", total is not 1";
				}
			  }catch(JSONException e) {
				e.printStackTrace();
				remark  = "JSON解析错误";
			  }
			}else {
			  try {
			    JSONObject object = new JSONObject(result);
			    remark = object.getString("message");
			    logger.error(remark);
			  }catch(JSONException e) {
			    e.printStackTrace();
			    remark  = "JSON解析错误";
			  }
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		logger.info("小组未分配- 通过报账单查询 ---------------end ---------");
	}

	/**
	 * 通过groupid查询到组员信息
	 */
    public String getUserId(String groupId) {
      logger.info(" 通过工作组ID: " + groupId +"查找组员 ");
    	String userId = null;
        group = new AccountGroupWork();
        AccountingPoolGroupUserBean bean = null;
       
        bean = group.get(groupId);
       
        if(bean == null) {
          status = false;
          remark = "没有可选的组员";
        	logger.error("没有可选的组员：");
        }else {
        	userId = bean.getCrewId();
        	remark = bean.toString();
        	logger.info("可选组员信息： " + bean.toString());
        }
    	return userId;
    }
	
    /**
     * 通过groupid查询到组员信息
     */
    public AccountingPoolGroupUserBean getCrewByGroupId(String groupId) {
        String userId = null;
        group = new AccountGroupWork();
        AccountingPoolGroupUserBean bean = null;
       
        bean = group.get(groupId);
       
        if(bean == null) {
            logger.error("没有可选的组员：");
        }else {
            userId = bean.getCrewId();
        }
        return bean;
    }
    
	
	public void assigning(String groupId) {
		
		String params = procTaskInfoList;
		
		String url = "";
		accountAuditUser = getCrewByGroupId(groupId);
		logger.info("通过小组号： "+ groupId + "得到组员 : " + accountAuditUser.toString());
			String userId = accountAuditUser.getCrewId();
			params = params + "],\"userId\":"+userId+"}";
			logger.info("小组未分配-重新分配- 初审审核，直接指派给"+accountAuditUser.getCrewEmpName() + " " +accountAuditUser.getCrewEmpCode()+" ---------------start ---------");
			if(actId == 1) {
	            url = Constants.ASSIGNING_URL;
	        }else if(actId == 2) {
	            url = Constants.REVIEW_ASSIGNING_URL;
	        }else {
	            url = Constants.ASSIGNING_URL;
	        }
	
		
		try {
		//	System.out.println("params---- " +params);
			result = HttpHelper.post( params, url);
			logger.info("assigning--------" + result);
		}catch(Exception e) {
			throw new AutoException("重新分配小组组员异常");
		}
		logger.info("小组未分配- 重新分配 ---------------end ---------");
	}
	
	
/*	public void adminUser() {
		String params = "{processInstanceId\":\""+proid+"\"}";
		String url = PropertiesUtil.getValue("accountingpool", "getTasksByProcInstIdUrl");
		try {
			Map<String,String> map = new HashMap<String,String>();
			//map.put("name", "Authorization");
			map.put("Authorization", "Basic Y3JjX2Vtczo5MmQ3ZGRkMmEwMTBjNTk1MTFkYzI5MDViN2UxNGY2NA==");
			result = HttpHelper.postAdminUser(map, params, url);
			System.out.println("grouping--------" + result);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}*/
	

}
